import { Observer } from "@/utils/observer/Observer";
import { ApiAndaUtil } from "@/utils/biz/information/customapi/ApiAndaUtil";
import { ApiLiYangUtil } from "@/utils/biz/information/customapi/ApiLiYangUtil";

import { ApiShanghaiUtil } from "@/utils/biz/information/customapi/ApiShanghaiUtil";

import { ApiTongDaFuYuAnUtil } from "@/utils/biz/information/customapi/ApiTongDaFuYuAnUtil";
import { ApiScheduleWallUtil } from "@/utils/biz/information/customapi/ApiScheduleWallUtil";
import { ApiSystemScheduleUtil } from "@/utils/biz/information/customapi/ApiSystemScheduleUtil";
import { UserCommitApi } from "@/api/user_common";
import { objectIsEq, resetLongToStr } from "@/utils/biz/common/BizUtils";
import { ApiAnLongXianUtil } from "@/utils/biz/information/customapi/ApiAnLongXianUtil";
import { ApiShangHaiShiYiXianUtil } from "@/utils/biz/information/customapi/ApiShangHaiShiYiXianUtil";

/**
 * 统一消息入口
 * 消息观察者 -- 信息发布屏
 */
class InformationCommonObserverBiz extends Observer {
  constructor(self, deviceInfo = {}, item) {
    super();
    // 外部组件
    this.catcheInfo = self;
    // 设备信息
    this.deviceInfo = deviceInfo;
    // 当前组件信息
    this.currentInfo = item || {};
    // 接口配置
    this.apiData = self.apiData;
  }


  /**
   * 消息监听入口
   * @param bizType
   * @param msgContent
   */
  async update(bizType, msgContent) {
    let self = this.catcheInfo;
    try {
      switch (bizType) {
        // 排班墙 消息监听
        case "Terminal_Schedule_Wall_TerminalData":
          await this.setDataByMsg(msgContent);
          break;
        // 医生信息
        case "Irms_Terminal_Doctor":
          await this.setDataOnlyByMsg(msgContent);
          break;
      }
    }catch (e) {
      console.error("消息数据加载失败："+ msgContent)
      self.handleException("sdkBizServices", "安卓消息消费异常 -- "+bizType+" -- >", JSON.stringify(e.stack));
    }
  }

  /**
   * 初始化
   * @returns {Promise<void>}
   */
  async init() {
    // 获取数据源
    await this.getDataSource();
    // 定时刷新
    this.comSetInterval();
  }

  /**
   * 获取数据源
   * @param backstageRefresh
   * @returns {Promise<void>}
   */
  async getDataSource(backstageRefresh) {
    let self = this.catcheInfo;
    if (this.currentInfo.screenDataType.indexOf("ApiInfo") === -1) {
      return;
    }
    try {
      // 配置接口标识 特质逻辑
      if (2 === self.apiData.reqKey) {
        if (self.apiData.ApiSign !== "") {
          let apiType = self.apiData.ApiSign;
          let resultData = [];
          switch (apiType) {
            case "api_schedule_info":
              // 查询排班
              resultData = await ApiSystemScheduleUtil.getScheduleListByTerminal(self, this.apiData);
              await this.resetData(resultData, backstageRefresh)
              break;
            case "api_schedule_wall_info":
              // 查询排班
              resultData = await ApiScheduleWallUtil.getSchedulingWallNew(self, this.apiData);
              await this.resetData(resultData, backstageRefresh)
              break;
            case "api_schedule_scheduling_info_alone":
              // 排班墙 -- 小屏
              resultData = await ApiScheduleWallUtil.schedulingInfoAlone(self, this.apiData);
              await this.resetData(resultData, backstageRefresh)
              break;
            case "custom_anda_room_doctor":
              // 安达 医生信息
              resultData = await ApiAndaUtil.customAndaRoomDoctor(self, this.apiData);
              await this.resetData(resultData, backstageRefresh)
              break;
            case "custom_anlongxian_worker_list":
              // 安龙县 医生信息
              resultData = await ApiAnLongXianUtil.customAndaRoomDoctor(self, this.apiData);
              await this.resetData(resultData, backstageRefresh)
              break;
            case "custom_shanghaishiyi_prescription_list":
              // 上海市第一医院 -- 获取药房数据
              resultData = await ApiShangHaiShiYiXianUtil.getPrescriptionList(self, this.apiData);
              await this.resetData(resultData, backstageRefresh)
              break;
            case "custom_tongdafuyuan_syncSurgeryData":
              // 通大附院手术视图
              resultData = await ApiTongDaFuYuAnUtil.syncSurgeryData(self, this.apiData);
              await this.resetData(resultData, backstageRefresh)
              break;
            case "custom_shanghai_syncSurgeryData":
              // 上海第一人民医院
              resultData = await ApiShanghaiUtil.syncSurgeryData(self, this.apiData);
              await this.resetData(resultData, backstageRefresh)
              break;

            case "custom_liyang_scheduleShown":
              // 溧阳 信息发布屏查询号源
              resultData = await ApiLiYangUtil.scheduleShown(self, this.apiData);
              await this.resetData(resultData, backstageRefresh)
              break;
            case "custom_liyang_examItem":
              // 溧阳 信息发布屏-检查项目公示
              resultData = await ApiLiYangUtil.examItem(self, this.apiData);
              await this.resetData(resultData, backstageRefresh)
              break;
            case "custom_liyang_expertIntroduce":
              // 溧阳 信息发布屏-专家简介
              resultData = await ApiLiYangUtil.expertIntroduce(self, this.apiData);
              await this.resetData(resultData, backstageRefresh)
              break;
          }
        }
      } else {
        if (self.apiData.reqUrl !== "") {
          // 获取接口数据
          let apiParams = self.apiData.apiParams;
          let formJson = {};
          if (objectIsEq(apiParams, "Object")) {
            formJson = {...apiParams};
          }
          // 是否内置设备参数,是的话直接拼接上
          if(true){
            formJson['terminalId'] = this.deviceInfo.screenId;
            formJson['terminalType'] = this.deviceInfo.screenType;
          }
          const {code, data} = await UserCommitApi.getChangeDataSource(self.apiData,formJson);
          if (200 === code) {
            this.resetData(data, backstageRefresh);
          }
        } else {

        }
      }

    } catch (e) {
      self.handleException("sdkBizServices", "接口异常 -- getDataSource -- >", JSON.stringify(e.stack));
    }
  }
  /**
   * 获取排班数据
   */
  async api_schedule_info() {
    let self = this.catcheInfo;
    // 获取午别
    const res = await UserCommitApi.getNoonList({
      tenantId: this.deviceInfo.hospitalId
    })
    // 全部午别信息
    let nooList = [];
    if (res.code === 200) {
      nooList = res.data || [];
    }
    if (nooList.length === 0) {
      this.resetData([]);
      return;
    }
    const formJson = {
      terminalId: this.deviceInfo.screenId,
      terminalType: this.deviceInfo.screenType,
      tenantId: this.deviceInfo.hospitalId
    };
    const { code, data } = await UserCommitApi.getScheduleListByTerminal(formJson)
    if (200 === code) {
      // 处理排班数据
      const scheduleList = data || [];
      let resultList = [];
      // 根据医生分组
      const workerGroupArr = scheduleList.reduce((result, item) => {
        const key = item['workerId'];
        if (!result[key]) {
          result[key] = [];
        }
        result[key].push(item);
        return result;
      }, {});

      for (let workerId in workerGroupArr) {
        const workerScheduleList = [];
        // 初始化午别数据
        nooList.forEach((item) => {
          let tempRow = {
            noonId: item.noonId + "",
            startTime: item.startTime,
            noonName: item.noonName,
          };
          self.weekDays.forEach((weekKey, index) => {
            tempRow[weekKey] = {
              status: false,
              week: index
            }
          })
          workerScheduleList.push(tempRow);
        });
        // 开始渲染数据
        const tempList = workerGroupArr[workerId];
        // 开始组装数据
        tempList.forEach((item) => {
          // 获取星期机key
          let weekKey = self.weekDays[parseInt(item.week)];
          let tempNoonIds = item.noonIds ? item.noonIds.split(',') : [];
          for (let workerScheduleListElement of workerScheduleList) {
            // 变更状态
            if (tempNoonIds.includes(workerScheduleListElement.noonId + "")) {
              workerScheduleListElement[weekKey].status = true;
            }
          }
        });
        resultList.push({
          workerInfo: workerGroupArr[workerId][0].workerDetailInfo,
          orderNum: workerGroupArr[workerId][0].orderNum,
          scheduleList: workerScheduleList
        })
        // 排序
        resultList = resultList.sort(function (a, b) {
          return a.orderNum = b.orderNum;
        })
      }
      this.resetData(resultList);
    }
  }

  /**
   * 重置数据
   * @param data
   * @param backstageRefresh
   */
  resetData(data, backstageRefresh) {
    let self = this.catcheInfo;
    if (this.currentInfo.screenDataType.indexOf("ApiInfo") === -1) {
      return;
    }

    if (self.apiData.switchState === false) {
      this.setData(data);
    }
    if (true === backstageRefresh) {
      this.setDataGroupOnly(data);
    } else {
      this.setSetIntervalGroup(data);
    }
    this.openEmptyData(data);
  }

  /**
   * 检错空数据清空
   */
  openEmptyData(data) {
    let self = this.catcheInfo;

    if (false === self.apiData.backstageRefresh) {
      return;
    }
    if (self.emptyDataInterval != null) {
      clearInterval(self.emptyDataInterval);
    }
    self.emptyDataInterval = null;
    let that = this;
    // 单个报到
    if (objectIsEq(data, "Array")) {
      if (self.apiData.groupData < 2) {
        self.emptyDataInterval = setInterval(async function () {
          await that.getDataSource();
          // 请求接口.
        }, self.apiData.refreshNum * 1000);
      }
    }
  }

  /**
   * 定时刷新接口
   */
  comSetInterval() {
    let self = this.catcheInfo;
    // 开启了
    if (self.apiData.backstageRefresh === true) {
      return;
    }
    // 设置分组数据
    if (self.apiData.refreshNum > 0) {
      try {
        console.info("接口请求定时器正在执行：————————————");
        let that = this;
        setInterval(async function () {
          await that.getDataSource();
          // 请求接口
        }, self.apiData.refreshNum * 1000);
      } catch (e) {
        self.handleException("sdkServices", "comSetInterval --> getDataSource执行异常", JSON.stringify(e.stack));
      }
    }
  }
  /**
   * 设置切屏数据 切屏参数来自后台
   */
  setDataOnlyByMsg(str) {
    const obj = JSON.parse(resetLongToStr(str));
    // 发送消息
    let msgContent = obj.msgContent || {};
    if (msgContent && typeof msgContent != 'string') {
      msgContent = JSON.parse(msgContent);
    }
    this.setData(msgContent || {})
  }

  /**
   * 设置切屏数据 切屏参数来自后台
   */
  async setDataByMsg(str) {
    let self = this.catcheInfo;
    const obj = JSON.parse(resetLongToStr(str));
    // 获取下标值
    const index = obj.msgContent;
    if (Number(index) >= 0 && self.apiData.groupData.length > 0 && self.apiData.groupData.length > index) {
      // 设置当前下标
      self.currentDataIndex = Number(index);
      if (self.apiData.groupData.length > self.currentDataIndex) {
        // 发送消息
        this.setData(self.apiData.groupData[self.currentDataIndex] || [])
      }
    } else {
      try {
        console.info("收到刷新全量数据请求：————————————");
        await this.getDataSource();
      } catch (e) {
        self.handleException('sdkServices', 'comSetInterval --> getDataSource 收到刷新全量数据请求 执行异常', JSON.stringify(e.stack));
      }
    }

  }

  /**
   * 定时器分组
   * @param data
   */
  setSetIntervalGroup(data = []) {
    let self = this.catcheInfo;

    if (self.apiData.switchState === false) {
      return;
    }
    if (self.groupSetInterval != null) {
      clearInterval(self.groupSetInterval);
    }
    // 设置分组数据
    if (self.apiData.scrollNumber > data.length) {
      this.setData(data);
      return;
    }
    self.apiData.groupData = this.groupBy(data, self.apiData.scrollNumber);
    let that = this;
    if (self.apiData.groupData.length > 0) {
      try {
        console.info("切屏定时任务定时器正在执行：————————————");
        let index = 0;
        if (self.currentDataIndex !== -1) {
          index = self.currentDataIndex;
        }
        if (index > self.apiData.groupData.length - 1) {
          index = 0;
        }
        // 请求接口
        this.setData(self.apiData.groupData[index] || []);
        // 是否主动设置数据，当开启了切屏才行
        if (true === self.apiData.setData) {
          index++;
          self.groupSetInterval = setInterval(async function () {
            // 强制刷新
            if (self.beginIndex === 0) {
              index = 0;
              self.beginIndex = -1;
            }
            console.info("切屏次数：————————————" + index);
            let isLast = false;
            // 如果是最后一屏 刷新数据
            if (self.apiData.backstageRefresh === true) {
              // 最后一次切屏刷新全量数据，重新分组
              if (self.apiData.groupData.length === 1 || index === self.apiData.groupData.length - 1) {
                // 无感刷新
                isLast = true;
              }
            }
            if (self.apiData.groupData.length === 1) {
              index = 0;
            }
            if (self.apiData.groupData.length - 1 >= index) {
              that.setData(self.apiData.groupData[index] || []);
              index++;
            } else {
              index = 0;
              that.setData(self.apiData.groupData[index] || []);
            }
            if (isLast) {
              await that.getDataSource(self.apiData.backstageRefresh);
            }
            // 请求接口
          }, self.apiData.switchTime * 1000);
        } else {
          // 如果是主屏，就发送切屏请求
          if (true === self.apiData.isMainScreen) {
            switch (self.apiData.isMainScreenCode) {
              // 主屏类型
              case "sendSchedulingWallCuttingScreen":
                this.sendSchedulingWallCuttingScreen();
                break;
            }
          }
        }
      } catch (e) {
        this.handleException("sdkServices", "groupSetInterval --> groupSetInterval 写入数据异常", JSON.stringify(e.stack));
      }
    } else {
      this.setData([]);
    }
  }

  /**
   * 设置分组数据
   * @param data
   */
  setDataGroupOnly(data) {
    this.apiData.groupData = this.groupBy(data, this.apiData.scrollNumber);
    this.beginIndex = 0;
  }

  /**
   * 设置数据
   * @param data
   */
  setData(data) {
    let self = this.catcheInfo;
    if (this.currentInfo.screenDataType.indexOf("ApiInfo") === -1) {
      return;
    }
    try {
      const formRef = self.$refs["vFormRef"];
      if (formRef) {
        formRef.executeChildMethod(this.currentInfo?.id, "publishListInfo", data);
      }
    } catch (e) {
      self.handleException("sdkBizServices", "内部组件异常 -- setData -- >", JSON.stringify(e.stack));
    }

  }

  //分组
  groupBy(arr, groupSize) {
    let chunks = [];
    for (let i = 0; i < arr.length; i += groupSize) {
      chunks.push(arr.slice(i, i + groupSize));
    }
    return chunks;
  }

  /**
   * 排班墙
   * 发送切屏请求
   */
  sendSchedulingWallCuttingScreen() {
    let self = this.catcheInfo;
    let index = 0;
    if (self.currentDataIndex !== -1) {
      index = self.currentDataIndex;
    }
    if (index > self.apiData.groupData.length - 1) {
      index = 0;
    }
    UserCommitApi.schedulingWallNextPage({ pageNum: index, });
    self.groupSetInterval = setInterval(async function () {
      console.info("切屏次数：————————————" + index);
      if (self.apiData.groupData.length === 1) {
        index = 0;
      }
      if (self.apiData.groupData.length - 1 > index) {
        index++;
      } else {
        index = 0;
      }
      // 获取午别
      const { code, data } = await UserCommitApi.schedulingWallNextPage({
        pageNum: index,
      });
      if (code !== 200) {
        console.warn("发送切屏数据失败");
      }
      // 请求接口
    }, self.apiData.switchTime * 1000);
  }


}

export { InformationCommonObserverBiz };
